{% extends 'cms/base.html' %}
{% block title %}发布新闻{% endblock %}
{% block header %}
    <!-- select2-bootstrap4  -->
    <link rel="stylesheet" href="{% static 'adminLTE/plugins/select2/css/select2.min.css' %}">
    <link rel="stylesheet" href="{% static 'adminLTE/plugins/select2-bootstrap4-theme/select2-bootstrap4.min.css' %}">

{% endblock %}
{% block footer %}
    <!-- ueditor  -->
    <script src="{% static 'ueditor/ueditor.config.js' %}"></script>
    <script src="{% static 'ueditor/ueditor.all.min.js' %}"></script>
    <script src="{% static 'ueditor/lang/zh-cn/zh-cn.js' %}"></script>
    <!-- select2-bootstrap4  -->
    <script src="{% static 'adminLTE/plugins/select2/js/select2.full.min.js' %}"></script>
    <!-- qiniu  -->
    <script src="https://unpkg.com/qiniu-js@2.5.5/dist/qiniu.min.js"></script>
    <script type="text/javascript">
        //Initialize Select2 Elements
        $('.select2bs4').select2({
            theme: 'bootstrap4'
        })


        function News() {
            var self = this
            self.progress = $('.progress')
            self.progressBar = self.progress.find('.progress-bar')
            self.qiniuDomain = 'http://qc4jmu41k.bkt.clouddn.com/'
        }

        News.prototype.listenUploadEvent = function () {
            var self = this
            var uploadServer = $('.upload-file-server')
            var uploadQiniu = $('.upload-file-qiniu')
            uploadServer.click(function () {
                var fileInput = $('<input type="file" name="file">')
                fileInput.trigger('click')
                fileInput.change(function () {
                    var file = this.files[0]
                    var formData = new FormData()
                    formData.append('file', file)
                    xfzajax.post({
                        url: '/cms/upload/',
                        data: formData,
                        processData: false,
                        contentType: false,
                        success: function (res) {
                            if (res.code === 200) {
                                swal({
                                    type: 'success',
                                    title: res.message,
                                    text: res.data.name,
                                    timer: 2000,
                                    onClose: function () {
                                        $('input[name=thumbnail]').val(res.data.url)
                                    }
                                })
                            } else {
                                swal({
                                    type: 'error',
                                    title: res.message,
                                    timer: 2000,
                                })
                            }
                        }
                    })
                })
            })
            uploadQiniu.click(function () {
                var fileInput = $('<input type="file" name="file">')
                fileInput.trigger('click')
                fileInput.change(function () {
                    var file = this.files[0]
                    var filename = (new Date()).getTime() + '.' + file.name.split('.')[file.name.split('.').length - 1];
                    // 七牛配置
                    var putExtra = {
                        fname: filename,
                        params: {},
                        mimeType: ["image/png", "image/jpeg", "image/gif"] // 'video/mp4'
                    };
                    var config = {
                        useCdnDomain: true,
                        retryCount: 6,
                        region: qiniu.region.z2
                    };

                    // token
                    xfzajax.get({
                        url: '/cms/token/',
                        success: function (res) {
                            if (res.code === 200) {
                                var token = res.data.token
                                // 上传
                                var observable = qiniu.upload(file, filename, token, putExtra, config)
                                observable.subscribe({
                                    next: function (res) {
                                        self.progress.show()
                                        var percent = res.total.percent.toFixed(2)
                                        self.progressBar.text(percent)
                                        self.progressBar.css({'width': percent + '%'})
                                    },
                                    error: function (err) {
                                        swal({
                                            type: 'error',
                                            title: err.message,
                                            timer: 1500
                                        })
                                        self.progress.hide()
                                        self.progressBar.text('0%')
                                        self.progressBar.css({'width': 0})
                                    },
                                    complete: function (res) {
                                        $('input[name=thumbnail]').val(self.qiniuDomain + res.key)
                                        self.progress.hide()
                                        self.progressBar.text('0%')
                                        self.progressBar.css({'width': 0})
                                    },
                                })
                            } else {
                                swal({
                                    type: 'error',
                                    title: res.message,
                                    timer: 1500,
                                })
                            }
                        }
                    })
                })
            })
        }
        News.prototype.createEditor = function () {
            var self = this
            window.ue = UE.getEditor('ueditor', {
                initialFrameHeight: 400,
                serverUrl: '/ueditor/upload/',
            })
        }
        News.prototype.listenSubmitEvent = function () {
            var self = this
            $('.submit-btn').click(function (e) {
                e.preventDefault()
                var titleInput = $('input[name=title]')
                var descInput = $('input[name=desc]')
                var thumbnailInput = $('input[name=thumbnail]')
                var categoryInput = $('select[name=category]')
                xfzajax.post({
                    url: window.location.pathname,
                    data: {
                        title: titleInput.val(),
                        desc: descInput.val(),
                        thumbnail: thumbnailInput.val(),
                        category: categoryInput.val(),
                        content: window.ue.getContent()
                    },
                    success: function (res) {
                        if (res.code === 200) {
                            swal({
                                type: 'success',
                                title: res.message,
                                timer: 1500,
                            })
                        } else {
                            swal({
                                type: 'error',
                                title: '失败~~',
                                timer: 1500,
                            })
                        }
                    }
                })
            })
        }
        News.prototype.run = function () {
            var self = this
            self.listenUploadEvent()
            self.createEditor()
            self.listenSubmitEvent()

        }
        $(function () {
            var news = new News()
            news.run()
        })
    </script>
{% endblock %}
{% block content-header %}
    发布新闻
{% endblock %}
{% block content %}
    <div class="row">
        <div class="col-lg-12">
            <div class="card card-primary card-outline">
                <div class="card-header">
                    <h3 class="card-title">编写新闻</h3>
                </div>
                <form role="form">
                    <div class="card-body">
                        <div class="form-group">
                            <label>标题</label>
                            <input type="text" class="form-control" placeholder="标题" name="title"
                                   value="{{ news.title }}">
                        </div>
                        <div class="form-group">
                            <label>描述</label>
                            <input type="text" class="form-control" placeholder="描述" name="desc"
                                   value="{{ news.desc }}">
                        </div>
                        <div class="form-group">
                            <label>封面</label>
                            <div class="input-group">
                                <input type="text" class="form-control" placeholder="封面地址" name="thumbnail"
                                       value="{{ news.thumbnail }}">
                                <span class="input-group-append">
                                    <button type="button" class="btn btn-default upload-file-server">上传至服务器</button>
                                </span>
                                <span class="input-group-append">
                                    <button type="button" class="btn btn-primary upload-file-qiniu">上传至七牛云</button>
                                </span>
                            </div>
                            <div class="progress" style="display: none">
                                <div class="progress-bar bg-primary progress-bar-striped" role="progressbar"
                                     aria-valuemin="0" aria-valuemax="100" style="width: 0">0%
                                </div>
                            </div>
                        </div>
                        <div class="form-group">
                            <label>分类</label>
                            <select class="custom-select select2bs4" name="category">
                                <option value="0">--请选择分类--</option>
                                {% for category in categories %}

                                    {% if news and news.category == category.id %}
                                        <option value={{ category.id }} selected>{{ category.name }}</option>
                                    {% endif %}
                                    <option value={{ category.id }}>{{ category.name }}</option>
                                {% endfor %}

                            </select>
                        </div>
                        <div class="form-group">
                            <label>内容</label>
                            {#                            <textarea style="width: 100%;height: 150px;" name="content" id="editor"></textarea>#}
                            <script id="ueditor" type="text/plain">{{ news.content|safe }}</script>
                        </div>
                    </div>
                    <!-- /.card-body -->

                    <div class="card-footer">
                        <button type="submit" class="btn btn-primary float-right submit-btn" data-pk="{{ news.id }}">发布</button>
                    </div>
                </form>
            </div>
        </div>
    </div>
{% endblock %}